package com.book.dao;

import com.book.pojo.Book;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * author:rengl
 * 2023-04-08 08:07
 * 模拟持久层,纯java状态下从内存中查询List
 */
public class BookMapper {

    private List<Book> list = new ArrayList();

    public Integer add(Book book) {
        //设置id,模拟数据库id自增
        book.setId(list.size()==0?1:list.get(list.size()-1).getId()+1);
        list.add(book);
        return 1;
    }

    public List<Book> findAll() {
        return list;
    }

    public Book findOne(Integer id) {
        for (Book book : list) {
            if(id.equals(book.getId())){
                return book;
            }
        }
        return null;
    }

    public Integer update(Book updatebook) {
        for (Book book : list) {
            if(book.getId().equals(updatebook.getId())){
                book.setName(updatebook.getName());
                book.setAuthor(updatebook.getAuthor());
                book.setPage(updatebook.getPage());
                return 1;
            }
        }
        return 0;
    }

    public Integer delete(Integer id) {
        Iterator<Book> iterator = list.iterator();
        while (iterator.hasNext()){
            Book book = iterator.next();
            if(book.getId().equals(id)){
                iterator.remove();
                return 1;
            }
        }
        return 0;
    }
}
